package com.gin.kotlin.no_gay_alliance.provider.ngaphp

import com.gin.kotlin.no_gay_alliance.callback.RCallback
import com.gin.kotlin.no_gay_alliance.model.ItemTypeModel
import com.gin.nga.enums.param.ItemType
import com.gin.nga.main.NgaApi
import com.gin.nga.response.base.SingleData
import com.gin.nga.response.item.ItemTypeInfo
import java.lang.ref.WeakReference

class ItemTypeProvider private constructor() : AbstractCachedDataProvider<List<Pair<Int, Int>>, SingleData<LinkedHashMap<String, ItemTypeInfo>>, List<ItemTypeModel>>(
    TYPE_FACTORY.constructCollectionLikeType(List::class.java, ItemTypeModel::class.java)
) {
    override val dir = "ITEM_TYPE"

    override fun transform(rawData: SingleData<LinkedHashMap<String, ItemTypeInfo>>) = rawData.data?.values?.map { ItemTypeModel(it) } ?: listOf()

    override fun requestMethod(ngaApi: NgaApi, params: List<Pair<Int, Int>>?) = ngaApi.itemApi.info(paramToList(params))

    /**
     * 查询单一类型的道具类型信息
     * @param itemType ItemType
     * @param id List<Int>
     * @param ignoreCache Boolean
     * @param callback RCallback<List<ItemTypeModel>, List<Pair<Int, Int>>>
     */
    fun enqueue(itemType: ItemType, id: List<Int>, ignoreCache: Boolean = false, callback: RCallback<List<ItemTypeModel>, List<Pair<Int, Int>>>) {
        enqueue(id.sorted().map { Pair(itemType.id, it) }, ignoreCache = ignoreCache, callback = callback)
    }

    override fun obtainRelativePath(userId: Long, params: List<Pair<Int, Int>>?) = "${paramToList(params).joinToString(",")}.json"

    companion object {
        private fun paramToList(params: List<Pair<Int, Int>>?) = (params ?: throw RuntimeException("必须提供参数")).flatMap { listOf(it.first, it.second) }
        private var instance: WeakReference<ItemTypeProvider> = WeakReference(ItemTypeProvider())
        fun getInstance(): ItemTypeProvider = instance.get() ?: ItemTypeProvider().also { instance = WeakReference(it) }
    }
}